import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, userRoutes, adminRoutes } from '@/router'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    isAdmin: false,
    userId: '',
    shopId: ''
    // resultRoutes:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ISADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  SET_SHOPID: (state, shopId) => {
    state.shopId = shopId
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_RESULTROUTES: (state, routes) => {
    state.resultRoutes = routes
    router.addRoutes(state.resultRoutes)
  }
}

const actions = {
  // 原版
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user login
  // 实践中，我们会经常用到 ES2015 的参数解构来简化代码（特别是我们需要调用 commit 很多次的时候）：{commit}参数解构
  // async login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   // 这下面的login调用的是上门开头引入的api/user的login
  //   // const res = await login({ username: username.trim(), password: password })
  //   const res = await login({ username: username.trim(), password: password })
  //   console.log(res)
  //   if (res.code === 20000 || res.code === 200) {
  //     // vuex里面保存token
  //     commit('SET_TOKEN', res.data.token)
  //     // 这个是调用/utils/auth里面的方法，保存token到cookie
  //     setToken(res.data.token)
  //     return 'ok'
  //   } else {
  //     return Promise.reject(new Error('账号密码错误'))
  //   }
  // },
  async login({ commit }, userInfo) {
    // const { username, password } = userInfo
    // 这下面的login调用的是上门开头引入的api/user的login
    // const res = await login({ username: username.trim(), password: password })
    const res = await login(userInfo)
    console.log(res)
    if (res.code === 20000 || res.code === 200) {
      // vuex里面保存token
      commit('SET_TOKEN', res.data.token)
      // 这个是调用/utils/auth里面的方法，保存token到cookie
      setToken(res.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('账号密码错误'))
    }
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          console.log('在store/modules/user.js获取用户信息失败')
          return reject('获取用户信息失败')
        }
        console.log('在store/modules/user.js/80行，输出getinfo的数据', data)
        const { isAdmin, shopId, userId } = data
        console.log('@@@@----', isAdmin, shopId, userId)

        commit('SET_ISADMIN', isAdmin)
        commit('SET_SHOPID', shopId)
        commit('SET_USERID', userId)
        if (isAdmin) {
          commit('SET_RESULTROUTES', adminRoutes)
        } else {
          commit('SET_RESULTROUTES', userRoutes)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

